package ciyuan.Network;

import ciyuan.DataManager.PlayerDataManager;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.network.PacketBuffer;
import net.minecraft.world.World;
import net.minecraftforge.fml.network.NetworkEvent;
import net.minecraftforge.fml.network.PacketDistributor;

import java.util.function.Supplier;

public class LivingPacket {

    private final CompoundNBT playerNBT;

    public LivingPacket(PacketBuffer buffer) {
        playerNBT = buffer.readNbt();
    }

    public LivingPacket(CompoundNBT playerNBT) {
        this.playerNBT = playerNBT;
    }

    public void toBytes(PacketBuffer buf) {
        buf.writeNbt(playerNBT);
    }

    public void handler(Supplier<NetworkEvent.Context> ctx) {
        if (ctx.get().getDirection().getOriginationSide().isClient()) {
            ctx.get().enqueueWork(() -> {
                World world = ctx.get().getSender().getLevel();
                String playerName = ctx.get().getSender().getName().getString();
                NetWorkRegister.INSTANCE.send(PacketDistributor.PLAYER.with(() -> ctx.get().getSender()), new LivingPacket(
                        PlayerDataManager.getSinglePlayerData(world, playerName)
                ));
            });
        } else {
            PlayerDataManager.setClientPlayerData(playerNBT);
        }
        ctx.get().setPacketHandled(true);
    }
}